﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Krile.Kernel;
using Krile.Kernel.Plugin.Operations.AgentElements;
using System.IO;
using Twinkle.Tweak;

namespace Twinkle.PluginImpl
{
    public class StatusControl : IStatusControl
    {
        public bool RecvGlobalTimeline { get; set; }

        public void ReceiveStatuses()
        {
            Common.AutoReceiver.Receive();
        }

        public bool Updatable
        {
            get
            {
                foreach (var a in TwitterCommonOperation.EnumeratePostableAccounts())
                    return true;
                return false;
            }
        }

        public OperationResult<object> Update(string text, ulong replyto, object affixObject)
        {
            return TwitterCommonOperation.Update(text, replyto, affixObject);
        }

        public bool Destroiable
        {
            get { return true; }
        }

        public bool AutoCreateFavOperationTriggers
        {
            get { return true; }
        }

        public bool AutoCreateReplyOperationTriggers
        {
            get { return true; }
        }

        public bool AutoCreateDeleteOperationTriggers
        {
            get { return true; }
        }

        public OperationResult<object> Destroy(ulong uid)
        {
            var sid = Kernel.Storage.GetSid(uid);
            if (sid == null)
                throw new InvalidOperationException("UID not found.");
            var status = Bridge.StatusManager.GetStatus(uid) as Tweak.TStatus;
            long nid = 0;
            if (status == null || status.User == null || status.User.Id == null || !long.TryParse(status.Id, out nid))
                throw new InvalidOperationException("Invalid status registered.");
            foreach (var acc in Kernel.Config.Accounts)
            {
                if (acc.UserId == status.User.Id)
                {
                    // invoke delete
                    var del = acc.CredentialProvider.DestroyStatus(nid);
                    if (del == null)
                        throw new InvalidOperationException();
                    return new OperationResult<object>() { OperationUri = new Uri("http://internal"), Succeeded = true };
                }
            }
            throw new InvalidOperationException("Account not found.");
        }

        public OperationResult<object> SetFavorite(ulong uid, bool create)
        {
            return TwitterCommonOperation.SetFavorite(uid, create);
        }

        public ulong GetUidFromServiceStatusId(string id)
        {
            return Kernel.Storage.GetUid(id);
        }

        public bool ServiceStatusIdExists(string id)
        {
            return Kernel.Storage.GetUid(id) != 0;
        }
    }
}
